package org.algorithm.二师兄.数组.三月.第三周;

import org.junit.Test;

import java.util.Arrays;

/**
 * @Date 2022/3/13 23:32
 * @Created by biubiu
 * @Link {https://leetcode-cn.com/problems/frequency-of-the-most-frequent-element/}
 */
public class 颜色分类 {


    @Test
    public  void test(){
        int[] nus = {1,2,0};
        sortColors(nus);
        System.out.println(Arrays.toString(nus));
    }

    public void sortColors(int[] nums) {
        if(nums == null || nums.length<2){
            return ;
        }
        int len = nums.length;
        /**
         * [0,P0) == 0
         * [P0,i) == 1
         * (p2,len-1] == 2
         */
        //确保每个区间初始化为空区间
        int p0 = 0;
        int i = 0;
        int p2 = len-1;
        while(i<= p2){
            if(nums[i] == 0){
                swap(nums,i,p0);
                p0++;
                i++;
            }else if(nums[i] == 1){
                i++;
            }else {
                swap(nums,i,p2);
                p2--;
            }
        }
    }

    private void swap(int[] nums,int index1,int index2){
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}
